<script lang="ts" setup>
// import type { DemoTableApi } from '../mock-api';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { useVbenModal, z } from '@vben/common-ui';

import { ElButton, ElTag } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
// import { MOCK_API_DATA } from '../table-data';

import { ref } from 'vue';

import { Country_Region_obj } from '@vben/constants';
import { $t } from '@vben/locales';
import { isHttpUrl } from '@vben/utils';

import dayjs from 'dayjs';

import {
  CarSelectApi,
  fileUploadR2PartComplete,
  getDownloadUrlApi,
  VideoAddApi,
  VideoDeleteApi,
  VideoEditApi,
  VideoListApi,
} from '#/api';
import VideoUploadSlice from '#/components/VideoUploadSlice.vue';

const refVideo = ref(null);
const Car_Options = ref([]);
const isVideoEdit = ref(false);
const id = ref('');
const colors = ['primary', 'success', 'warning'];
const gridOptions: VxeGridProps = {
  showOverflow: true,
  columns: [
    { title: '序号', type: 'seq' },
    { field: 'videName', title: '视频名称' },
    {
      field: 'carType',
      title: '绑定的车型',
      slots: { default: 'carType' },
    },
    {
      field: 'carArea',
      title: '车型绑定的地区',
      slots: { default: 'carArea' },
    },
    { field: 'videRemark', title: '备注' },
    {
      field: 'uploadTimestamp',
      title: '上传时间',
      slots: { default: 'uploadTimestamp' },
    },
    {
      field: 'action',
      title: '操作',
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await VideoListApi({
          offset: page.currentPage,
          size: page.pageSize,
        });
        return {
          items: res.records,
          total: res.total,
        };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
});
const [BaseForm, formApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      fieldName: 'ossObjectKey',
      label: '视频',
      defaultValue: [],
      rules: z.object({}).array().nonempty('请选择该视频'),
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '视频名称',
    },
    {
      component: 'Select',
      fieldName: 'carIds',
      label: '选择车型',
      componentProps: {
        filterable: true,
        multiple: true,
        options: Car_Options,
      },
      rules: z.string().array().nonempty('请选择该视频对应的车型'),
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: '备注',
    },
  ],
});
const handleSubmitData = (data) => {
  const res = { ...data };
  // res.carIds = data.carIds;
  res.ossObjectKey = data.ossObjectKey[0];
  return res;
};
const [Modal, modalApi] = useVbenModal({
  onConfirm: () => {
    formApi
      .validate()
      .then((res) => {
        return res.valid ? Promise.resolve() : Promise.reject();
      })
      .then(() => {
        return formApi.getValues();
      })
      .then(async (res) => {
        modalApi.setState({ loading: true });
        // const keys = await fileUploadR2(res.ossObjectKey, {
        //   key: 'videoOssObjectKey',
        //   value: 'videoUrl',
        // });
        // return { ...res, ossObjectKey: keys };
        if (res?.ossObjectKey[0].videoOssObjectKey) {
          return {
            ...res,
            ossObjectKey: [res?.ossObjectKey[0].videoOssObjectKey],
          };
        } else {
          const data = await refVideo.value[0].sliceUpload();
          await fileUploadR2PartComplete(
            data.videoOssObjectKey,
            data.uploadId,
            data.etagList,
          );
          return { ...res, ossObjectKey: [data.videoOssObjectKey] };
        }
      })
      .then((res2) => {
        return isVideoEdit.value
          ? VideoEditApi(handleSubmitData(res2))
          : VideoAddApi(handleSubmitData(res2));
      })
      .then(() => {
        modalApi.setState({ loading: false });
        modalApi.close();
        gridApi.reload();
      })
      .catch(() => {
        modalApi.setState({ loading: false });
      });
  },
});
const openModal = () => {
  modalApi.setState({ loading: true });
  modalApi.open();
  CarSelectApi()
    .then((res) => {
      Car_Options.value = res.map((item) => {
        return {
          label: item.showName,
          value: item.id,
        };
      });
      modalApi.setState({ loading: false });
    })
    .catch(() => {
      modalApi.setState({ loading: false });
    });
};
const handleDetailsData = (data) => {
  const res = { ...data };
  res.carIds = data.carInfos.map((item) => item.id);
  res.name = data.videName;
  res.remark = data.videRemark;
  res.ossObjectKey = [
    {
      videoUrl: data.videoUrl,
      videoOssObjectKey: data.videoSooObjectKey,
    },
  ];
  return res;
};
const [DeleModal, deleModalApi] = useVbenModal({
  onConfirm: () => {
    deleModalApi.setState({ loading: true });
    VideoDeleteApi({ ids: [id.value] })
      .then(() => {
        deleModalApi.close();
        gridApi.reload();
      })
      .finally(() => {
        deleModalApi.setState({ loading: false });
      });
  },
});
const addVideo = () => {
  isVideoEdit.value = false;
  openModal();
};
const editVideo = async (row) => {
  isVideoEdit.value = true;
  id.value = row.id;
  if (row.videoOssObjectKey && !row.videoUrl && !isHttpUrl(row.videoUrl)) {
    const res = await getDownloadUrlApi(row.videoOssObjectKey);
    row.videoUrl = res;
  }
  formApi.setValues(handleDetailsData(row), false);
  openModal();
};
const deleVideo = (row) => {
  id.value = row.id;
  deleModalApi.open();
};
</script>

<template>
  <div class="vp-raw w-full">
    <Grid class="my-table-row-height">
      <template #toolbar-tools>
        <ElButton class="mr-2" type="primary" @click="addVideo">
          添加视频素材
        </ElButton>
      </template>
      <template #action="{ row }">
        <ElButton type="text" @click="editVideo(row)">编辑</ElButton>
        <ElButton type="text" @click="deleVideo(row)">删除</ElButton>
      </template>
      <template #uploadTimestamp="{ row }">
        {{ dayjs(Number(row.uploadTimestamp)).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #carType="{ row }">
        <div v-for="(tag, ti) in row.carInfos" :key="tag.id">
          <ElTag :type="colors[ti % 3]">
            {{ tag.showName }}
          </ElTag>
        </div>
      </template>
      <template #carArea="{ row }">
        <div v-for="(tag, ti) in row.carInfos" :key="tag.id">
          <template v-for="(item, i) in tag.area" :key="item">
            <ElTag :type="colors[ti % 3]">
              {{ $t(Country_Region_obj[item].lan) }}
            </ElTag>
          </template>
        </div>
      </template>
    </Grid>
    <Modal class="w-[600px]" title="添加视频素材">
      <BaseForm>
        <template #ossObjectKey="data">
          <VideoUploadSlice ref="refVideo" v-bind="data" />
        </template>
      </BaseForm>
    </Modal>
    <DeleModal title="删除视频">
      <div class="flex flex-col gap-[10px]">
        <div>您确定删除该视频？</div>
        <div>注意：删除后，该视频无法再展示至用户端。</div>
      </div>
    </DeleModal>
  </div>
</template>
<style lang="scss" scoped>
:deep(.my-table-row-height) {
  --vxe-ui-table-row-height-small: 'auto';
}
</style>
